import time
import tornado.web
import tornado.gen
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
class SleepHandler(tornado.web.RequestHandler):
    executor = ThreadPoolExecutor(4) #起线程池，由当前RequestHandler持有
    @tornado.gen.coroutine
    def get(self):
        print('sleep')
        a= time.time()
        result = yield self.block_task(a) #block_task将提交给线程池运行
        self.write(str(result))
    
    @run_on_executor
    def block_task(self, a):
        print('sleep', a)
        time.sleep(2) #也可能是其他耗时／阻塞型任务
        return time.time()-a #直接return结果即可


class JustNowHandler(tornado.web.RequestHandler):
    executor = ThreadPoolExecutor(4) #起线程池，由当前RequestHandler持有
    @tornado.gen.coroutine
    def get(self):
        print('index')
        a= time.time()
        result = yield self.block_task(a) #block_task将提交给线程池运行
        self.write(str(result))
    
    @run_on_executor
    def block_task(self, a):
        print('index', a)
        time.sleep(2) #也可能是其他耗时／阻塞型任务
        return time.time()-a #直接return结果即可

if __name__ == "__main__":
    #tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[
    (r"/sleep", SleepHandler), (r"/", JustNowHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
